<template>
	<div>
		<game-box>
			<template #config>
				<div class="h-full w-full bg-[#2a364f] px-[12px] py-[16px]">
					<BetAmount
						v-if="!isDesktop"
						:type="type"
						:isRuning="type === 'auto' ? isRuning : false"
						:amount="amount"
						:showMax="maxbet"
						:isDisabled="isAutoDisabled"
						@changeMoneyDisabled="changeMoneyDisabled"
						@changeAmount="changeAmount" />
					<StartBtn
						v-if="!isDesktop"
						@handleClick="handleStart"
						:type="type"
						stopIcon="plinko"
						:debounceTime="0"
						:stoping="stoping"
						:isRuning="type === 'auto' ? isRuning : false"
						:isDisabled="isInitBtnDisabled || isMoneyDisabled" />
					<SwitchTab
						v-if="isDesktop"
						:class="!isDesktop ? 'mt-4' : ''"
						:type="type"
						:isRuning="type === 'auto' ? isRuning : isInitBtnDisabled"
						:isDisabled="type === 'auto' ? isDisabled : isInitBtnDisabled"
						:maxbet="maxbet"
						:mute="mute"
						:rocket="rocket"
						@changeMode="changeMode" />
					<div class="h-group-t"></div>
					<BetAmount
						v-if="isDesktop"
						:type="type"
						:isRuning="type === 'auto' ? isRuning : false"
						:amount="amount"
						:showMax="maxbet"
						:isDisabled="isAutoDisabled"
						@changeMoneyDisabled="changeMoneyDisabled"
						@changeAmount="changeAmount" />
					<div class="h-group-t" v-if="isDesktop"></div>
					<RiskRroup
						:riskMaps="riskTextMap()"
						:risk="risk"
						:type="type"
						:isRuning="isRuning"
						:isDisabled="isDisabled"
						@changeRisk="changeRisk" />
					<div class="h-group-t"></div>
					<SlideRow
						:type="type"
						:isRuning="isRuning"
						:isDisabled="isDisabled"
						:defaultValue="rows"
						@handleChange="changeRows" />
					<template v-if="type === 'auto'">
						<div class="h-group-t"></div>
						<LoopCount
							@changeLoop="changeLoop"
							:type="type"
							:loopNum="loopNum"
							:isRuning="isRuning"
							:isDisabled="isDisabled" />
					</template>
					<div v-if="isDesktop">
						<StartBtn
							:type="type"
							stopIcon="plinko"
							:isRuning="type === 'auto' ? isRuning : false"
							:isDisabled="isInitBtnDisabled || isMoneyDisabled"
							:stoping="stoping"
							:debounceTime="0"
							@handleClick="handleStart" />
						<div class="h-group-t"></div>
					</div>
					<SwitchTab
						v-if="!isDesktop"
						:class="!isDesktop ? 'mt-4' : ''"
						:type="type"
						:isRuning="type === 'auto' ? isRuning : isInitBtnDisabled"
						:isDisabled="type === 'auto' ? isDisabled : isInitBtnDisabled"
						:maxbet="maxbet"
						:mute="mute"
						:rocket="rocket"
						@changeMode="changeMode" />
				</div>
			</template>
			<template #content>
				<div ref="gameContent" class="h-full w-full bg-[#1B2538]"></div>
			</template>
		</game-box>
		<result-dialog
			:showDialog="showResult"
			:betId="resultBetId"
			:gameObj="mPlinkoGame"
			gameType="plinko"
			@close="closeResultDialog" />
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import GameBox from '../components/game-box/index.vue'
import StartBtn from '../components/common/start-button.vue'
import RiskRroup from '../components/common/risk-groups.vue'
import BetAmount from '../components/common/bet-amount.vue'
import SwitchTab from '../components/common/switch-tab.vue'
import SlideRow from '../components/common/slide-row.vue'
import LoopCount from '../components/common/loop-count.vue'
import ResultDialog from '../components/dialog/result.vue'
import { loadJs, getCurrencyIcon, message } from '@/utils'
import { isDesktop } from '@/hooks'
import { playPlinko, gameEndSettled } from '@/api/third/mini-games'
import { useWalletStore, useAccountStore, useAppStore } from '@/store'
// import { THIRD_GAME } from '@/constants/global-key'
import { AccountShowType } from '@/types'
import { eventBus } from '@/views/games/eventBus'
import { qlaunchUrl } from '../getUrlT'
import { showError } from '@/utils'
import { transformationAmount, resultSquareClick } from '../util'
import { pinkoConfigString, riskTextMap, delayGameTime } from '@/views/games/config'

const token = computed(() => accountStore.token)
// import { debounce } from 'lodash-es'
const accountStore = useAccountStore()
const walletStore = useWalletStore()
const appStore = useAppStore()
const type = ref('manual')
const rows = ref(10)
const isRuning = ref(false)
const isDisabled = ref(true)
const isInitBtnDisabled = ref(true)
const isMoneyDisabled = ref(false)
const stoping = ref(false)
const isAutoDisabled = ref(true)
const risk = ref('MEDIUM_RISK')
const amount = ref<any>(0)
const rocket = ref(false)
const mute = ref(false)
const maxbet = ref(false)
const loopNum = ref(0)
const gameContent = ref(null)
const showResult = ref(false)
const resultBetId = ref('')
let mPlinkoGame: any = null
const timeInter = ref(1500)
const PlinkoRiskLevel: any = ref({})
let interval: any = null
let languageMap: any = null
let allIsBallFlying: boolean = true

watch(
	token, // 监听计算属性 token
	(newVal: any, oldVal: any) => {
		if (newVal !== oldVal) {
			qlaunchUrl()
		}
	}
)
watch(
	() => appStore.lang,
	(val: string) => {
		mPlinkoGame?.setLanguage(languageMap?.[val])
	}
)
const currencyIcon = computed(() => {
	const { selectedFiatCurrency, displayCryptoInFiat, selectedCryptoCurrency } =
		walletStore.walletConfig
	return displayCryptoInFiat ? selectedFiatCurrency : selectedCryptoCurrency
})
watch(currencyIcon, (val) => {
	mPlinkoGame?.setCurrency(getCurrencyIcon(val))
})
onMounted(() => {
	mPlinkoGame = null
	qlaunchUrl()
	initGame()
	eventBus.on('changeRocket', (val: any) => {
		console.log(val, 'changeRocket')
		rocket.value = val
		mPlinkoGame?.setAccelerationMode(val)
		timeInter.value = val ? 300 : 1500
	})
	eventBus.on('changeMaxBet', (val: any) => {
		console.log(val)
		maxbet.value = val
	})
	eventBus.on('changeMute', (val: boolean) => {
		console.log(val)
		mute.value = val
		mPlinkoGame?.setSoundEffect(!val)
	})
})
onUnmounted(() => {
	allIsBallFlying = true
	restTimeAuto()
	// 注销游戏
	mPlinkoGame.destroy()
	mPlinkoGame = null
	// 在组件卸载时移除监听器
	eventBus.off('changeRocket', () => {
		// 空的回调函数
	})
	eventBus.off('changeMaxBet', () => {
		// 空的回调函数
	})
	eventBus.off('changeMute', () => {
		// 空的回调函数
	})
})
const changeMoneyDisabled = (status: boolean) => {
	isMoneyDisabled.value = status
}
const gameEnd = async (betId: string) => {
	if (!betId) return
	await gameEndSettled({
		round: betId
	})
}
const initGame = () => {
	loadJs('/gameLib.js').then((originalGameLib: any) => {
		console.log('originalGameLib', originalGameLib)
		PlinkoRiskLevel.value = originalGameLib.PlinkoRiskLevel
		let Language = originalGameLib.Language
		// let Currency = originalGameLib.Currency
		let ThemeMode = originalGameLib.ThemeMode
		languageMap = {
			zh: Language.ZH,
			zhTW: Language.zhTW,
			en: Language.EN
		}

		mPlinkoGame = new originalGameLib.PlinkoGame({
			parentElement: gameContent.value,
			backgroundColor: 'rgba(0, 9, 58, 0)',
			language: languageMap[appStore.lang],
			currencyIcon: getCurrencyIcon(currencyIcon.value),
			riskLevel: PlinkoRiskLevel.value[risk.value],
			numberOfRows: rows.value,
			plinkoConfig: pinkoConfigString,
			themeMode: ThemeMode.NIGHT,
			soundEffect: false,
			onGameResultSquareClick,
			onGameEndiingResultSquareClick,
			onGameLoadEnd: () => {
				mPlinkoGame.setNumberOfRows(rows.value)
				restTimeAuto()
				isInitBtnDisabled.value = false
			}
		})
		mPlinkoGame.setSoundEffect(true)
	})
}

const onGameResultSquareClick = async (betId: string) => {
	console.log('点击结果')
	resultBetId.value = betId
	showResult.value = true
}

const closeResultDialog = () => {
	showResult.value = false
}
const onGameEndiingResultSquareClick = (
	resultIndex: any,
	numberOfRows: any,
	multiplier: number
) => {
	console.log(resultIndex, numberOfRows, multiplier, 'multiplier')
	return resultSquareClick(multiplier, amount.value)
}

const restTimeAuto = (auto = false) => {
	if (allIsBallFlying) {
		isRuning.value = false
		isDisabled.value = false
		isAutoDisabled.value = false
	}
	interval && clearInterval(interval)
	if (auto) {
		setTimeout(() => {
			message.success('自动投注完成', { duration: 5000 })
		}, 500)
	}
}
const handleStart = async () => {
	allIsBallFlying = false
	if (type.value === 'auto') {
		console.log('auto')
		if (isRuning.value) {
			stoping.value = true
			setTimeout(() => {
				if (allIsBallFlying) {
					stoping.value = false
				}
				restTimeAuto(true)
			}, delayGameTime)
		} else {
			message.success('自动投注开始', { duration: 5000 })
			isDisabled.value = true
			isRuning.value = true
			isAutoDisabled.value = true
			if (loopNum.value === 0) {
				isRuning.value = true
				interval = setInterval(() => {
					playGame()
				}, timeInter.value)
			}
			if (loopNum.value > 0) {
				interval = setInterval(() => {
					playGame()
					loopNum.value--
					if (loopNum.value === 0) {
						if (!allIsBallFlying) {
							stoping.value = true
						}
						restTimeAuto(true)
					}
				}, timeInter.value)
			}
		}
	} else {
		isDisabled.value = true
		isRuning.value = true
		console.log('开始')
		await playGame()

		isRuning.value = false
	}
}

const playGame = async () => {
	if (!accountStore.token) {
		accountStore.showAccount(AccountShowType.login)
		return
	}
	try {
		if (stoping.value) return
		const { data } = await playPlinko({
			amount: transformationAmount(amount.value),
			currency: walletStore.balanceCur?.currency,
			identifier: 'plinko',
			risk: risk.value,
			rows: rows.value
		})
		mPlinkoGame && mPlinkoGame.addGameResult(data.id, data.state.plinkoResult, onEnd)

		//V2.0.1版本修改的方法

		// Process the data here
	} catch (error: any) {
		interval && clearInterval(interval)
		isDisabled.value = false
		isRuning.value = false
		isAutoDisabled.value = false
		showError(error)
	}
}

const onEnd = (isBallFlying: boolean, betId: any) => {
	allIsBallFlying = !isBallFlying
	if (!isBallFlying) {
		isRuning.value = false
		isDisabled.value = false
		isAutoDisabled.value = false
		stoping.value = false
	}
	console.log(betId, 'Game Over' + isBallFlying)
	gameEnd(betId)
	// walletStore.getBalance(0)
}

const changeLoop = (val: string) => {
	console.log(val)
	loopNum.value = parseInt(val)
}

const changeRows = (val: number) => {
	console.log(val)
	rows.value = val
	mPlinkoGame && mPlinkoGame.setNumberOfRows(val)
}

const changeRisk = (val: string) => {
	risk.value = val
	mPlinkoGame && mPlinkoGame.setRiskLevel(PlinkoRiskLevel.value[risk.value])
}

const changeAmount = (val: string) => {
	console.log(val)
	amount.value = val
}

// const changeRocket = (val: boolean) => {
// 	console.log(val)
// 	rocket.value = val
// 	mPlinkoGame?.setAccelerationMode(val)
// 	timeInter.value = val ? 200 : 1000
// }

// const changeMaxBet = (val: boolean) => {
// 	console.log(val)
// 	maxbet.value = val
// }

// const changeMute = (val: boolean) => {
// 	console.log(val)
// 	mute.value = val
// 	mPlinkoGame.setSoundEffect(!val)
// }

const changeMode = (val: string) => {
	type.value = val
}
</script>
